package com.train.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.common.enums.impl.BizExceptionEnums;
import com.train.common.exception.GlobalException;
import com.train.common.resp.PageResp;
import com.train.system.dto.trainstation.TrainStationAddOrEditDTO;
import com.train.system.dto.trainstation.TrainStationDTO;
import com.train.system.dto.trainstation.TrainStationPageDTO;
import com.train.system.mapper.TrainStationMapper;
import com.train.system.po.TrainStationPO;
import com.train.system.resp.trainstation.TrainStationDetailResp;
import com.train.system.resp.trainstation.TrainStationListResp;
import com.train.system.resp.trainstation.TrainStationPageResp;
import com.train.system.resp.trainstation.TrainStationResp;
import com.train.system.service.TrainService;
import com.train.system.service.TrainStationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author baitiaojun
 * @description 针对表【trainStation(火车车站)】的数据库操作Service实现
 * @createDate 2025-02-20 16:32:30
 */
@Service
@RequiredArgsConstructor
public class TrainStationServiceImpl extends ServiceImpl<TrainStationMapper, TrainStationPO>
    implements TrainStationService {

    private final TrainStationMapper trainStationMapper;

    private final TrainService trainService;

    @Override
    public void addOrEditTrainStation(TrainStationAddOrEditDTO trainStationAddOrEditDTO) {
        //校验车次是否存在
        trainService.validTrainCode(trainStationAddOrEditDTO.getTrainCode());

        //根据请求id判断是insert还是update
        if (trainStationAddOrEditDTO.getId() != null) {
            //如果是编辑,需要校验id记录是否存在
            if (!trainStationMapper.existsId(trainStationAddOrEditDTO.getId())) {
                throw new GlobalException(BizExceptionEnums.EXP_TRAIN_STATION_NOT_EXISTS);
            }

            //获取同车次下所有途经车站列表
            List<TrainStationDTO> trainStationDTOList = trainStationMapper.getTrainStationList(trainStationAddOrEditDTO.getTrainCode());

            //过滤掉被更新的途径站,收集为map
            Map<Integer, String> stationIndexNameMap = trainStationDTOList.stream()
                    .filter(trainStationDTO -> !trainStationDTO.getId().equals(trainStationAddOrEditDTO.getId()))
                    .collect(Collectors.toMap(TrainStationDTO::getIndex, TrainStationDTO::getName));

            //校验同车下其他途径车站的的站名或站序是否已存在
            if (stationIndexNameMap.containsKey(trainStationAddOrEditDTO.getIndex())
                    || stationIndexNameMap.containsValue(trainStationAddOrEditDTO.getName())) {
                throw new GlobalException(BizExceptionEnums.EXP_TRAIN_STATION_EXISTS);
            }

        } else {
            //新增就直接判断同车次下是否有相同站序或站名
            if (trainStationMapper.exists(trainStationAddOrEditDTO.getTrainCode(), trainStationAddOrEditDTO.getIndex(), trainStationAddOrEditDTO.getName())) {
                throw new GlobalException(BizExceptionEnums.EXP_TRAIN_STATION_EXISTS);
            }
        }

        //计算停车时间(时:分:秒)
        Duration duration = Duration.between(trainStationAddOrEditDTO.getInTime(), trainStationAddOrEditDTO.getOutTime());
        if (duration.isNegative()) {
            duration = Duration.ofSeconds(duration.getSeconds() + 86400);
        }
        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60;
        long seconds = duration.getSeconds() % 60;
        LocalTime timeDifference = LocalTime.of((int) hours, (int) minutes, (int) seconds);
        trainStationAddOrEditDTO.setStopTime(timeDifference);

        TrainStationPO trainStationPO = BeanUtil.copyProperties(trainStationAddOrEditDTO, TrainStationPO.class);
        boolean isSaved = this.saveOrUpdate(trainStationPO);
        if (!isSaved) {
            throw new GlobalException(BizExceptionEnums.EXP_ADD_TRAIN_STATION);
        }
    }

    @Override
    public PageResp<TrainStationPageResp> pageList(TrainStationPageDTO trainStationPageDTO) {
        return trainStationMapper.pageList(trainStationPageDTO);
    }

    @Override
    public void remove(Long id) {
        boolean isRemoved = this.removeById(id);
        if (!isRemoved) {
            throw new GlobalException(BizExceptionEnums.EXP_REMOVE_TRAIN_STATION);
        }
    }

    @Override
    public TrainStationDetailResp getTrainStationDetail(TrainStationDTO trainStationDTO) {
        return trainStationMapper.getTrainStationDetail(trainStationDTO);
    }

    @Override
    public List<TrainStationResp> getTrainStationByCode(List<String> trainCodes) {
        List<TrainStationPO> trainStationPOS = trainStationMapper.selectTrainStationByCode(trainCodes);
        return BeanUtil.copyToList(trainStationPOS, TrainStationResp.class);
    }

    @Override
    public List<TrainStationListResp> getTrainStationListByTrainCodes(List<String> trainCodes) {
        return trainStationMapper.getTrainStationListByTrainCodes(trainCodes);
    }
}




